iT邦幫忙

2021 iThome 鐵人賽

DAY 5
1

今日題目:75. Sort Colors(Medium)

Given an array nums with n objects colored red, white, or blue, sort them in-place so that objects of the same color are adjacent, with the colors in the order red, white, and blue.

We will use the integers 0, 1, and 2 to represent the color red, white, and blue, respectively.

You must solve this problem without using the library's sort function.

Example 1:
Input: nums = [2,0,2,1,1,0]
Output: [0,0,1,1,2,2]

Example 2:
Input: nums = [2,0,1]
Output: [0,1,2]

Example 3:
Input: nums = [0]
Output: [0]

Example 4:
Input: nums = [1]
Output: [1]

Constraints:

  • n == nums.length
  • 1 <= n <= 300
  • nums[i] is 0, 1, or 2.

思路:

由頭(i)和尾(j)開始兩兩比較,
j由後向前和i比較,
若j較i小,則ij交換
j全部比完後,則將向後移

My solution

class Solution:
    def sortColors(self, nums: List[int]) -> None:
        """
        Do not return anything, modify nums in-place instead.
        """
        n = len(nums)
        i=0
    
        for i in range(n):
            for j in range(n-1,i,-1):
                while j>i and nums[j] < nums[i]:
                    temp = nums[i]
                    nums[i] = nums[j]
                    nums[j] = temp

Result

https://ithelp.ithome.com.tw/upload/images/20210920/20140843sAmHJjViEd.png


上一篇
Day4- 15. 3Sum
下一篇
Day6-9. Palindrome Number
系列文
開學之前....20
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

1 則留言

0
阿瑜
iT邦研究生 4 級 ‧ 2021-09-21 00:24:58

Cool!
用swap的方式 做排序
把第一小,第二小...最後一個依序換到最前方來完成排序.
我好久沒實作排序啦,都直接alist.sort(),但這題不行直接
call sort.
Try Try this.(mark 兩行)(我還沒驗證)

class Solution:
    def sortColors(self, nums: List[int]) -> None:
        """
        Do not return anything, modify nums in-place instead.
        """
        n = len(nums)
        #i=0
    
        for i in range(n):
            for j in range(n-1,i,-1):
                while nums[j] < nums[i]: #
                    temp = nums[i]
                    nums[i] = nums[j]
                    nums[j] = temp

我剛剛試了
這樣子打美得斯哈哈哈
我使用swap的方式,我的i前面一定都是比他小的數字,所以要一個j>i的判斷式,避免他重複比較已經排好的

我要留言

立即登入留言